package com.itcast.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itcast.constant.MessageConstant;
import com.itcast.dao.MemberDao;
import com.itcast.dao.PermissionDao;
import com.itcast.dao.RoleDao;
import com.itcast.dao.UserDao;
import com.itcast.entity.PageResult;
import com.itcast.entity.QueryPageBean;
import com.itcast.entity.Result;
import com.itcast.pojo.Permission;
import com.itcast.pojo.Role;
import com.itcast.pojo.User;
import com.itcast.service.UserService;
import com.itcast.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

/**
 * @className: UserServiceImpl
 * @description: TODO 类描述
 * @author: Jng
 * @date: 2022/4/17
 **/

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    RoleDao roleDao;
    @Autowired
    PermissionDao permissionDao;
    @Autowired
    MemberDao memberDao;


    // 根据用户名查询用户基本信息和关联角色信息，同时需要查询角色关联的权限信息
    @Override
    public User findByUsername(String username) {
        //根据用户名获取用户
        User user= userDao.findByUsername(username);
        if (user==null){
            return null;
        }
        Integer id = user.getId();
        // 根据用户id查询对应的角色信息
        Set<Role> roles=roleDao.findRoleByUserId(id);
        for (Role role : roles) {
            Integer roleId = role.getId();
            // 根据角色id查询用户权限
            Set<Permission> permissions=permissionDao.findByRoleId(roleId);
            role.setPermissions(permissions);
        }
        user.setRoles(roles);
        return user;
    }

    @Override
    public Result registerUser(User user) {
        Boolean flag=false;
        if (user.getUsername()!=null&& user.getPassword()!=null){
            String password = user.getPassword();
            String s = MD5Utils.md5(password);
            user.setPassword(s);
            flag=userDao.registerUse(user);
            return new Result(flag,MessageConstant.ADD_USER_SUCCESS);
        }
        return new Result(flag,MessageConstant.ADD_USER_FAIL);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<User> lists= memberDao.findPage(queryString);
        return new PageResult(lists.getTotal(),lists.getResult());
    }

    @Override
    public boolean deleteById(Integer id) {
        return userDao.deleteById(id);
    }
}
